using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using BTSProjectWizard;
using System.Text;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Globalization;
using System.Resources;
using System.Threading;
namespace BTSRetryPatternWizard
{
	/// <summary>
	/// Summary description for UserControl1.
	/// </summary>
	public class RetryWizardPage : BTSWizardPage
	{
		Hashtable _paramsT = new Hashtable();
		string GenerateParamList()
		{
			ParameterInfo[] prms = _method.GetParameters();
			MemoryStream ms  = new MemoryStream();
			XmlTextWriter tw = new XmlTextWriter(ms,System.Text.Encoding.Default);
			//wizard.Add("dummyxml","<s:doc xmlns:s='http://Schema1'></s:doc>");
			tw.WriteStartDocument();
			tw.WriteStartElement("doc");
			
			StringBuilder sb = new StringBuilder();
			for(int i=0;i<prms.Length;i++)
			{
				tw.WriteStartElement("var");
				sb.Append(_paramsT[prms[i].Name].ToString());
				if(i<prms.Length-1)
					sb.Append(",");
				tw.WriteElementString("id",Guid.NewGuid().ToString());
				tw.WriteElementString("name",_paramsT[prms[i].Name].ToString());
				tw.WriteElementString("type",prms[i].ParameterType.ToString());

				tw.WriteEndElement();//var
				
			}
			

			tw.WriteEndElement();
			tw.WriteEndDocument();
			tw.Flush();
			ms.Flush();
			ms.Seek(0,SeekOrigin.Begin);
			StreamReader sr = new StreamReader(ms);
			string xml = sr.ReadToEnd();
			wizard.AddSymbol("dummyxml",xml);
			wizard.AddSymbol("paramslist",sb.ToString());
			sr.Close();
			tw.Close();
			ms.Close();
			
			return sb.ToString();

		}
		public override bool ProcessSymbols()
		{
			bool valid = ValidateParams();
			if(valid)
			{
				wizard.AddSymbol("assemblyname",_assembly.Text);
				Reference r = new Reference();
				r.Path = _asm.Location;
				wizard.Info.References.Add(r);
				wizard.AddSymbol("method",_methodName.Text);
				wizard.AddSymbol("class",_className.Text);
				wizard.AddSymbol("retry",_retry.Value);
				wizard.AddSymbol("returntype",_method.ReturnType.ToString());
				wizard.AddSymbol("params",_paramsT);
				string call = null;
				if(_method.ReturnType==typeof(void))
					call =String.Format("calledObj.{0}({1});",_methodName.Text,GenerateParamList());
				else
				{
					call = String.Format("returnValue =  calledObj.{0}({1});",_methodName.Text,GenerateParamList());
				}
				wizard.AddSymbol("call1",call);
				wizard.AddSymbol("call2","done = true;");////Make the original call&#xD;&#xA;returnValue =  calledObj.{0}(calledObj, methodName, paramArray); &#xD;&#xA;done = true;",m));));
				//wizard.AddSymbol("call",String.Format("//Make the original call&#xD;&#xA;returnValue =  calledObj.{0}(calledObj, methodName, paramArray); &#xD;&#xA;done = true;",_methodName.Text));

			}
			else
			{
				MessageBox.Show(_rm.GetString("RetryValidationError",Thread.CurrentThread.CurrentCulture));
			}
			return valid;

		}
		//Make sure all the params have names
		bool ValidateParams()
		{
			bool valid = true;
			if(_asm==null)
				valid = false;
			if(_method==null)
				valid = false;
			for(int i=0;i<_params.Items.Count;i++)
			{
				if(!_paramsT.ContainsKey(_params.Items[i].ToString()))
				{
					valid = false;
				}
				else
				{
					string v = _paramsT[_params.Items[i].ToString()].ToString();
					if(!ValidString(v))
						valid = false;

				}

				
			}
			return valid;

		}
		bool ValidString(string s)
		{
			if(s.Length==0||s=="")
				return false;
			else
				return true;
		}
		
		private System.Windows.Forms.Button _findAssembly;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.ComboBox _params;
		private System.Windows.Forms.ComboBox _methodName;
		private System.Windows.Forms.ComboBox _className;
		private System.Windows.Forms.TextBox _assembly;
		private System.Windows.Forms.NumericUpDown _retry;
		private System.Windows.Forms.OpenFileDialog _assemblyOpen;
		private System.Windows.Forms.TextBox _pName;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public RetryWizardPage()
		{
			// This call is required by the Windows.Forms Form Designer.
			InitializeComponent();
            

			// TODO: Add any initialization after the InitComponent call

		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if( components != null )
					components.Dispose();
			}
			base.Dispose( disposing );
		}

		#region Component Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify 
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RetryWizardPage));
            this._assembly = new System.Windows.Forms.TextBox();
            this._findAssembly = new System.Windows.Forms.Button();
            this._className = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this._methodName = new System.Windows.Forms.ComboBox();
            this._retry = new System.Windows.Forms.NumericUpDown();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this._params = new System.Windows.Forms.ComboBox();
            this.label6 = new System.Windows.Forms.Label();
            this._assemblyOpen = new System.Windows.Forms.OpenFileDialog();
            this._pName = new System.Windows.Forms.TextBox();
            ((System.ComponentModel.ISupportInitialize)(this._retry)).BeginInit();
            this.SuspendLayout();
            // 
            // _assembly
            // 
            resources.ApplyResources(this._assembly, "_assembly");
            this._assembly.Name = "_assembly";
            this._assembly.TextChanged += new System.EventHandler(this._assembly_TextChanged);
            // 
            // _findAssembly
            // 
            this._findAssembly.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            resources.ApplyResources(this._findAssembly, "_findAssembly");
            this._findAssembly.Name = "_findAssembly";
            this._findAssembly.Text = "Browse";
            this._findAssembly.Click += new System.EventHandler(this._findAssembly_Click);
            // 
            // _className
            // 
            resources.ApplyResources(this._className, "_className");
            this._className.Name = "_className";
            this._className.SelectedIndexChanged += new System.EventHandler(this._className_SelectedIndexChanged);
            // 
            // label1
            // 
            this.label1.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            resources.ApplyResources(this.label1, "label1");
            this.label1.Name = "label1";
            this.label1.Text = "Assembly";
            // 
            // label2
            // 
            this.label2.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            resources.ApplyResources(this.label2, "label2");
            this.label2.Name = "label2";
            this.label2.Text = "Class";
            // 
            // label3
            // 
            this.label3.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            resources.ApplyResources(this.label3, "label3");
            this.label3.Name = "label3";
            this.label3.Text = "Method";
            // 
            // _methodName
            // 
            resources.ApplyResources(this._methodName, "_methodName");
            this._methodName.Name = "_methodName";
            this._methodName.SelectedIndexChanged += new System.EventHandler(this._methodName_SelectedIndexChanged);
            // 
            // _retry
            // 
            this._retry.ContextMenu = null;
            resources.ApplyResources(this._retry, "_retry");
            this._retry.Name = "_retry";
            this._retry.Value = new decimal(new int[] {
            5,
            0,
            0,
            0});
            // 
            // label4
            // 
            this.label4.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            resources.ApplyResources(this.label4, "label4");
            this.label4.Name = "label4";
            this.label4.Text = "Retry Count";
            // 
            // label5
            // 
            this.label5.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            resources.ApplyResources(this.label5, "label5");
            this.label5.Name = "label5";
            this.label5.Text = "Param Name";
            // 
            // _params
            // 
            resources.ApplyResources(this._params, "_params");
            this._params.Name = "_params";
            this._params.SelectedIndexChanged += new System.EventHandler(this._params_SelectedIndexChanged);
            // 
            // label6
            // 
            this.label6.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            resources.ApplyResources(this.label6, "label6");
            this.label6.Name = "label6";
            this.label6.Text = "Params";
            // 
            // _assemblyOpen
            // 
            resources.ApplyResources(this._assemblyOpen, "_assemblyOpen");
            // 
            // _pName
            // 
            resources.ApplyResources(this._pName, "_pName");
            this._pName.Name = "_pName";
            this._pName.TextChanged += new System.EventHandler(this._pName_TextChanged);
            // 
            // RetryWizardPage
            // 
            this.Controls.Add(this._pName);
            this.Controls.Add(this.label6);
            this.Controls.Add(this._params);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label4);
            this.Controls.Add(this._retry);
            this.Controls.Add(this._methodName);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this._className);
            this.Controls.Add(this._findAssembly);
            this.Controls.Add(this._assembly);
            this.Name = "RetryWizardPage";
            resources.ApplyResources(this, "$this");
            this.Title = "Rety Pattern";
            this.Load += new System.EventHandler(this.RetryWizardPage_Load);
            ((System.ComponentModel.ISupportInitialize)(this._retry)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		private void RetryWizardPage_Load(object sender, System.EventArgs e)
		{
           
		}

		private void _findAssembly_Click(object sender, System.EventArgs e)
		{
			 _assemblyOpen.ShowDialog();
			_assembly.Text = _assemblyOpen.FileName;
		}

		private void _assembly_TextChanged(object sender, System.EventArgs e)
		{
			LoadAssembly(_assembly.Text);
		}
		Assembly _asm = null;
		void LoadAssembly(string asmname)
		{
			_asm = Assembly.LoadFrom(asmname);
			_className.Items.Clear();
			Type[] types = _asm.GetTypes();
			for(int i=0;i<types.Length;i++)
			{
				_className.Items.Add(types[i].FullName);
			}
		}
		Type _type;
		MethodInfo _method;
		private void _className_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			_methodName.Items.Clear();
			_type = _asm.GetType(_className.SelectedItem.ToString());
            MethodInfo[] methods =_type.GetMethods();//BindingFlags.Public|BindingFlags.InvokeMethod);
			for(int i=0;i<methods.Length;i++)
			{
				if(!methods[i].IsSpecialName)
					_methodName.Items.Add(methods[i].Name);
			}
		}

		private void _methodName_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if(_method!=null)
			{
				string msg = _rm.GetString("RetryChangeMethod",Thread.CurrentThread.CurrentCulture);
				string title = _rm.GetString("RetryChangeMethodTile",Thread.CurrentThread.CurrentCulture);
				DialogResult dr =  MessageBox.Show( this.Parent,msg,title,MessageBoxButtons.OKCancel);
				if(dr==DialogResult.Cancel)
					return;

			}
			_method = _type.GetMethod(_methodName.SelectedItem.ToString());
			_params.Items.Clear();
			_params.Text="";

			ParameterInfo[] prms = _method.GetParameters();
			for(int i=0;i<prms.Length;i++)
			{
				_params.Items.Add(prms[i].Name);
			}

		}

		private void _params_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			
			string param =_params.SelectedItem.ToString();
			if(_paramsT.ContainsKey(param))
			{
				_pName.Text = _paramsT[param].ToString();
			}
			else
				_pName.Text = "";
		}

		private void _pName_TextChanged(object sender, System.EventArgs e)
		{
			_paramsT[_params.SelectedItem.ToString()]=_pName.Text;

		}
	}
	public class Foo
	{
		public string Prop
		{
			set{_Prop=value;}
			get{return _Prop;}
		}
		string _Prop;
		public string One()
		{
			return "one";
		}
		public string Two(string p)
		{
			return "two";
		}
		public void Three()
		{
		}
		public void Four(string p,int i)
		{
		}
	}
}
